import { message } from 'antd';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';

type Result<T> = {
  data?: any;
  code: number;
  message: string;
  result: T;
};

const realLocale = {
  'zh-CN': 'zh-Hans',
  'en-US': 'en',
};

const baseURL: string = '';
const PREFIX_PATH = '';
export class CreateAxiosInstance {
  // axios 实例
  instance: AxiosInstance;
  // 基础配置，url和超时时间
  baseConfig: AxiosRequestConfig = {
    baseURL,
    timeout: 60000,
    // headers: {
    //   'Cache-control': 'no-cache'
    // }
  };

  constructor(config: AxiosRequestConfig = {}) {
    this.instance = axios.create(Object.assign(this.baseConfig, config));

    this.instance.interceptors.request.use(
      (config) => {
        config.url = PREFIX_PATH + config.url;

        const token = localStorage.getItem('token');
        if (token) {
          config.headers.set('Authorization', token);
        }

        return config;
      },
      (err: any) => {
        return Promise.reject(err);
      },
    );

    // 拦截data信息
    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        return res;
      },
      (err: any) => {
        if (err.response) {
          const { data, status } = err.response;
          if (data.code === 'file_is_used') {
            return;
          }
          if (data?.message) {
            message.error(data.message);
          }
        }

        return Promise.reject(err);
      },
    );
  }

  public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config);
  }

  public post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<Result<T>> {
    return this.instance.post(url, data, config);
  }

  public put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return this.instance.put(url, data, config);
  }

  public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config);
  }
}

const service = new CreateAxiosInstance();

export function request<TData extends any = any>(config: AxiosRequestConfig) {
  return service.instance(config).then((res) => {
    return res.data as TData;
  });
}

export { service };
